Skip to content

Conversation

@mgiannopoulos24
Copy link

Problem

When using the Tab key to navigate through links inside Swiper slides, the browser automatically scrolls the container to show the focused element. This changes the scrollLeft/scrollTop property of the wrapper element, which breaks the slider display and causes slides to become misaligned.

This issue affects keyboard accessibility, as users navigating with the Tab key would see the slider break visually.

Solution

The fix prevents the browser's automatic scroll from affecting the slider by:

  1. Listening for focusin events: Added a focusin event listener (which fires before focus and bubbles) to catch focus events on focusable elements (links, buttons, inputs, etc.) inside slides.
  2. Saving scroll position: When a focusable element gets focus, we immediately save the current scrollLeft/scrollTop of the wrapper element (or container in CSS mode).
  3. Restoring scroll position: We restore the saved scroll position immediately and repeatedly using requestAnimationFrame to catch any browser scroll that occurs during the focus event.
  4. Scroll event listener: Added a passive scroll event listener that restores the scroll position if the browser attempts to scroll during the restoration window (100ms).
  5. Slide navigation: If the focused element is in a different slide, we navigate to that slide after ensuring the scroll position is restored.

Changes

  • Modified src/modules/a11y/a11y.mjs:
    • Added scroll restoration state variables (savedScrollLeft, savedScrollTop, isRestoringScroll, scrollRestoreTimeout)
    • Created restoreScrollPosition() function to restore saved scroll positions
    • Created handleScroll() function to catch and restore scroll during focus events
    • Updated handleFocusIn() to save and restore scroll position for all focusable elements
    • Added scroll event listeners in init() and cleanup in destroy()
  • Added test demo: demos/4006-tab-focus-fix.html to verify the fix works correctly

Related Issues

Fixes #4006

@nolimits4web
Copy link
Owner

Can you provide maybe a demo which shows the issue? We already have similar logic within handleFocus here, and the demo you provided works perfectly fine with the latest swiper, nothing breaks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The slider display will inevitably break if a link, placed in one of the slides gets focused by tab key.

2 participants